# import boto3
from choreography.jobs_manager import get_next_job

# client = boto3.client('emr')
import emr.emr_job_handler as emr_job_handler
import ecs.ecs_job_handler as ecs_job_handler
import api.api_job_handler as api_job_handler


def handle_next_job(next_job, event, context):
    print("next job: %s" % next_job)
    if next_job["jobType"] == "emr":
        if event["source"] == "pt.spider":
            emr_job_handler.spider_completed_handler(next_job, event, context)
        elif event["source"] == "aws.emr":
            emr_job_handler.emr_completed_handler(next_job, event, context)
    elif next_job["jobType"] == "ecs":
        if event["source"] == "pt.spider":
            ecs_job_handler.spider_completed_handler(next_job, event, context)
        elif event["source"] == "aws.emr":
            ecs_job_handler.emr_completed_handler(next_job, event, context)
    elif next_job["jobType"] == "api":
        api_job_handler.completed_handler(next_job, event, context)


def event_completed_handler(event, context):
    """
    handle events only
    source == ['pt.spider', 'aws.emr'] and
    detail-type == ['Spider State-change Notification', 'EMR Step Status Change'] and
    detail.state == 'COMPLETED'
    :param event:
    :param context:
    :return:
    """
    print("triggered event_completed_handler: %s" % event)
    next_job = get_next_job(event)
    if isinstance(next_job, list):
        [handle_next_job(n, event, context) for n in next_job]
    elif isinstance(next_job, dict):
        handle_next_job(next_job, event, context)


